package com.ruoyi.system.outto.goods.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.V2.inter.mapper.ArtRecMapper;
import com.ruoyi.system.interAttr.domain.InterAttr;
import com.ruoyi.system.interAttr.mapper.InterAttrMapper;
import com.ruoyi.system.model.domain.ArtRec;
import com.ruoyi.system.model.domain.SalePartner;
import com.ruoyi.system.model.dto.GoodsInfoAndAttrValueDto;
import com.ruoyi.system.outto.goods.MONIXIZAIApi;
import com.ruoyi.system.outto.utils.GoodsInfoUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class MONIXIZAIApiImpl implements MONIXIZAIApi {
    @Autowired
    InterAttrMapper interAttrMapper;
    @Autowired
    GoodsInfoUtils goodsInfoUtils;
    @Autowired
    ArtRecMapper artRecMapper;

    private Map<String, Object> getParams(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner, Map<String, Object> params) {
        String substring = salePartner.getSaleName();
        InterAttr interAttr = interAttrMapper.selectInterAttrByConfig(substring, goodsInfoAndAttrValueDto.getGameId());
        String gameName = goodsInfoAndAttrValueDto.getGameName();

        params.put("categoryId", interAttr.getInterGameId());
        params.put("categoryName", interAttr.getInterGameName());
        params.put("price", goodsInfoAndAttrValueDto.getPrice());

        if (gameName.equals("王者荣耀")) {
            params.put("username", goodsInfoAndAttrValueDto.getAccountNumber().trim());// 账号
            params.put("type", 1);// 上传方式 0 登录营地号采集 1 营地ID采集
            params.put("password", "123456"); // 密码
            params.put("phone", goodsInfoAndAttrValueDto.getSecurityPhone());// 联系手机
            params.put("gamePlatform", 1);// 游戏平台
            params.put("sellerDesc", goodsInfoAndAttrValueDto.getDes());// 商品描述
        } else {
            params.put("tradeType", 2);// 销售类型
            params.put("aiValue", goodsInfoAndAttrValueDto.getAccountNumber().trim());// 账号
            params.put("name", goodsInfoAndAttrValueDto.getId() + "_" + goodsInfoAndAttrValueDto.getTitle());// 标题
            params.put("phone", goodsInfoAndAttrValueDto.getSecurityPhone());
            params.put("originalPrice", goodsInfoAndAttrValueDto.getPrice());
            params.put("applyidInfo", 1);
            params.put("whetherAdult", 1);// 是否成人
            params.put("secondaryName", 1);
            params.put("addService", "可投保");
            params.put("bindZzb", 0);
            params.put("accountOrigin", 1);// 账号类型 1 本人注册
            params.put("status", 1);
            params.put("tradeStatus", 0);// 默认 销售状态 0 待售 1 交易中 2 已售 5 已删除
            params.put("shenheStatus", 0);// 审核状态
            String logoImgUrl = uploadImg(goodsInfoAndAttrValueDto.getTitleImg(), salePartner, true);
            params.put("logo", logoImgUrl);
            params.put("imagel", JSONObject.toJSONString(goodsInfoUtils.getGoodsInfoImageList(goodsInfoAndAttrValueDto)));
        }

        Property(goodsInfoAndAttrValueDto, params, salePartner);

        return params;
    }

    private void Property(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map<String, Object> params, SalePartner salePartner) {
        String substring = salePartner.getSaleName();
        if (substring.contains("_")) {
            substring = substring.substring(salePartner.getSaleName().indexOf("_") + 1);
        }
        InterAttr interAttr = interAttrMapper.selectInterAttrByConfig(substring, goodsInfoAndAttrValueDto.getGameId());

        List<Map<String, Object>> dataList = new ArrayList<>();
        //开始匹配区服属性
        builderServer(goodsInfoAndAttrValueDto, params, interAttr.getServer());
        //开始匹配单选属性
        builderRadioAttr(goodsInfoAndAttrValueDto, params, dataList, interAttr.getRadioAttr());
        //开始匹配多选属性
        builderCheckAttr(goodsInfoAndAttrValueDto, params, dataList, interAttr.getCheckAttr());
        //开始匹配输入框属性
        builderInputAttr(goodsInfoAndAttrValueDto, params, dataList, interAttr.getInputAttr());

        params.put("gameJson", JSONObject.toJSONString(dataList));
    }

    private void builderServer(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map<String, Object> params, String serverAttr) {
        List<String> needDefaultAreaGameNameList = new ArrayList<>();
        needDefaultAreaGameNameList.add("穿越火线");
        // 区服为 三级，属性匹配只有两级，只要三级区服的匹配都需要额外添加
        if (goodsInfoAndAttrValueDto.getGameName().equals("穿越火线")) {
            params.put("area", "官服");
            params.put("cf_swin_sys_area", "官服");
        }
        JSONObject matchServerJson = goodsInfoUtils.matchGoodsServer(goodsInfoAndAttrValueDto, serverAttr);
        if (ObjectUtil.isNotEmpty(matchServerJson)) {
            JSONObject lastParentServer = getLastParentServer(matchServerJson, params);
            if (!needDefaultAreaGameNameList.contains(goodsInfoAndAttrValueDto.getGameName())) {
                params.put("area", lastParentServer.getString("name"));
            }
        }
    }

    private JSONObject getLastParentServer(JSONObject matchServerJson, Map<String, Object> params) {
        String parentServer = matchServerJson.getString("parent");
        if (StringUtils.isNotEmpty(parentServer)) {
            JSONObject jsonObject = JSONObject.parseObject(parentServer);
            String mapKey = jsonObject.getString("id").split("&")[1];
            params.put(mapKey, jsonObject.getString("name"));
            return getLastParentServer(jsonObject, params);
        }
        return matchServerJson;
    }

    private void builderRadioAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map<String, Object> params, List<Map<String, Object>> dataList, String radioAttr) {
        JSONObject matchRadioJson = goodsInfoUtils.matchGoodsRadioAttr(goodsInfoAndAttrValueDto, radioAttr);
        List<JSONObject> matchJsonList = JSONObject.parseArray(matchRadioJson.getString("match"), JSONObject.class);
        List<JSONObject> defaultJsonList = JSONObject.parseArray(matchRadioJson.getString("default"), JSONObject.class);
        // 单选匹配
        for (JSONObject matchJson : matchJsonList) {
            JSONObject matchData = matchJson.getJSONObject("matchData");
            String matchMapKey = matchJson.getString("id");
            if (matchMapKey.equals("isFace") || matchMapKey.equals("antiAddiction")) {
                params.put(matchMapKey, matchData.getString("id").split("&")[1]);
            } else {
                params.put(matchMapKey, matchData.getString("name"));
                Map<String, Object> dataListMap = new HashMap<>();
                dataListMap.put("key", matchMapKey);
                dataListMap.put("value", matchData.getString("name"));
                dataList.add(dataListMap);
            }
        }
        // 默认匹配
        for (JSONObject defaultJson : defaultJsonList) {
            JSONObject matchData = defaultJson.getJSONObject("matchData");
            String defaultMapKey = defaultJson.getString("defaultValue");
            if (defaultMapKey.equals("isFace") || defaultMapKey.equals("antiAddiction")) {
                params.put(defaultMapKey, matchData.getString("id").split("&")[1]);
            } else {
                params.put(defaultMapKey, matchData.getString("name"));
                Map<String, Object> dataListMap = new HashMap<>();
                dataListMap.put("key", defaultMapKey);
                dataListMap.put("value", matchData.getString("name"));
                dataList.add(dataListMap);
            }
        }

    }

    private void builderCheckAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map<String, Object> params, List<Map<String, Object>> dataList, String checkboxAttr) {
        JSONObject matchCheckboxJson = goodsInfoUtils.matchGoodsCheckboxAttr(goodsInfoAndAttrValueDto, checkboxAttr);
        List<JSONObject> matchJsonList = JSONObject.parseArray(matchCheckboxJson.getString("match"), JSONObject.class);
        List<JSONObject> defaultJsonList = JSONObject.parseArray(matchCheckboxJson.getString("default"), JSONObject.class);

        for (JSONObject matchJson : matchJsonList) {
            String matchMapKey = matchJson.getString("id");
            List<JSONObject> matchDataList = JSONObject.parseArray(matchJson.getString("matchData"), JSONObject.class);
            List<String> resultList = new ArrayList<>();
            for (JSONObject matchData : matchDataList) {
                String name = matchData.getString("name");
                resultList.add(name);
            }
            params.put(matchMapKey, resultList);
            Map<String, Object> dataListMap = new HashMap<>();
            dataListMap.put("key", matchMapKey);
            dataListMap.put("value", resultList);
            dataList.add(dataListMap);
        }
        // 默认匹配
        for (JSONObject defaultJson : defaultJsonList) {
            JSONObject matchData = defaultJson.getJSONObject("matchData");
            String defaultMapKey = defaultJson.getString("defaultValue");
            params.put(defaultMapKey, matchData.getString("name"));
            Map<String, Object> dataListMap = new HashMap<>();
            dataListMap.put("key", defaultMapKey);
            dataListMap.put("value", matchData.getString("name"));
            dataList.add(dataListMap);
        }
    }

    private void builderInputAttr(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, Map<String, Object> params, List<Map<String, Object>> dataList, String inputAttr) {
        JSONObject matchInputJson = goodsInfoUtils.matchGoodsInputAttr(goodsInfoAndAttrValueDto, inputAttr);
        List<JSONObject> matchJsonList = JSONObject.parseArray(matchInputJson.getString("match"), JSONObject.class);
        List<JSONObject> defaultJsonList = JSONObject.parseArray(matchInputJson.getString("default"), JSONObject.class);
        for (JSONObject matchJson : matchJsonList) {
            String matchMapKey = matchJson.getString("id");
            params.put(matchMapKey, matchJson.getString("matchData"));
            Map<String, Object> dataListMap = new HashMap<>();
            dataListMap.put("key", matchMapKey);
            dataListMap.put("value", matchJson.getString("matchData"));
            dataList.add(dataListMap);
        }
        for (JSONObject defaultJson : defaultJsonList) {
            String matchMapKey = defaultJson.getString("id");
            params.put(matchMapKey, "0");
            Map<String, Object> dataListMap = new HashMap<>();
            dataListMap.put("key", matchMapKey);
            dataListMap.put("value", "0");
            dataList.add(dataListMap);
        }
    }

    private String uploadImg(String imgUrl, SalePartner salePartner, boolean isLogo) {
        File file = goodsInfoUtils.uploadImgByImgUrl(imgUrl);
        String uploadImgUrl = "https://b.xizai.com/trade/serviceuploadSale/singlecard/file";
        if (!isLogo) {
            uploadImgUrl = "https://b.xizai.com/trade/serviceupload/";
        }
        String response = HttpRequest.post(uploadImgUrl)
                .header("Authorization", salePartner.getTwoOther())
                .form("file", file)
                .execute()
                .body();

        JSONObject resultJson = JSONObject.parseObject(response);
        String fileName = "";
        if (resultJson.getString("code").equals("0")) {
            fileName = resultJson.getString("fileBase") + resultJson.getString("fileUrl");
        }
        FileUtil.del(file);
        return fileName;
    }


    @Override
    public AjaxResult addGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> resultMap = new HashMap<>();
        String addGameUrl = "";
        String gameName = goodsInfoAndAttrValueDto.getGameName();
        if (gameName.equals("王者荣耀"))
            addGameUrl = "https://www.xizai.com/trade/business/back/campsiteByMerchant";
        else addGameUrl = "https://www.xizai.com/trade/businessAccount/accountInfo/addBusinessAccount";
        Map<String, Object> params = getParams(goodsInfoAndAttrValueDto, salePartner, new HashMap<>());
        String result = HttpRequest.post(addGameUrl)
                .header("authorization", salePartner.getTwoOther())
                .body(JSONObject.toJSONString(params))
                .execute()
                .body();
        log.info("请求参数:"+JSONObject.toJSONString(params));
        log.info("响应参数:"+result);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!resultJson.getString("code").equals("200")) {
            resultMap.put("code", 500);
        } else {
            resultMap.put("code", 200);
            if (ObjectUtil.isNotEmpty(resultJson.getJSONObject("data"))) {
                resultMap.put("outId", resultJson.getJSONObject("data").getString("accountId"));
            } else {
                String accountListUrl = "https://www.xizai.com/trade/business/back/accountList?pageNum=1&pageSize=10&isShelf=5&aiValue=" + goodsInfoAndAttrValueDto.getAccountNumber();
                String accountListResult = HttpRequest.get(accountListUrl)
                        .header("authorization", salePartner.getTwoOther())
                        .execute()
                        .body();
                JSONObject accountListResultJson = JSONObject.parseObject(accountListResult);
                if (accountListResultJson.getString("code").equals("200")) {
                    JSONObject accountJson = JSONObject.parseArray(accountListResultJson.getString("rows"), JSONObject.class).get(0);
                    resultMap.put("outId", accountJson.getString("id"));
                }
            }
        }
        resultMap.put("req", JSONObject.toJSONString(params));
        resultMap.put("res", resultMap);
        resultMap.put("msg", resultJson.getString("data"));
        return AjaxResult.success(resultMap);
    }

    @Override
    public AjaxResult editGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> resultMap = new HashMap<>();
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        String selectUrl = "https://www.xizai.com/trade/businessAccount/accountInfo/getAccountInfoByBusiness/" + artRecs.get(0).getOutid();
        String selectResult = HttpRequest.get(selectUrl)
                .header("authorization", salePartner.getTwoOther())
                .execute()
                .body();
        JSONObject selectResultJson = JSONObject.parseObject(selectResult);
        if (!"200".equals(selectResultJson.getString("code"))) {
            resultMap.put("code", 500);
            resultMap.put("req", JSONObject.toJSONString("11006413"));
            resultMap.put("res", selectResult);
            resultMap.put("msg", selectResultJson.getString("msg"));
        } else {
            Map data = selectResultJson.getObject("data", Map.class);
            Map<String, Object> params = getParams(goodsInfoAndAttrValueDto, salePartner, data);
            String updateUrl = "https://www.xizai.com/trade/businessAccount/accountInfo/updateBusinessAccount";
            String result = HttpRequest.post(updateUrl)
                    .header("authorization", salePartner.getTwoOther())
                    .body(JSONObject.toJSONString(params))
                    .execute()
                    .body();
            JSONObject resultJson = JSONObject.parseObject(result);
            if (!"200".equals(resultJson.getString("code"))) {
                resultMap.put("code", 500);
            } else {
                resultMap.put("code", 200);
            }
            resultMap.put("req", JSONObject.toJSONString(params));
            resultMap.put("res", result);
            resultMap.put("msg", resultJson.getString("msg"));
        }
        return AjaxResult.success(resultMap);
    }

    @Override
    public AjaxResult delGame(GoodsInfoAndAttrValueDto goodsInfoAndAttrValueDto, SalePartner salePartner) {
        Map<String, Object> resultMap = new HashMap<>();
        ArtRec artRecreq = new ArtRec();
        artRecreq.setConfig(salePartner.getId());
        artRecreq.setAccountId(goodsInfoAndAttrValueDto.getId());
        List<ArtRec> artRecs = artRecMapper.selectArtRecList(artRecreq);
        String downOnUrl = "https://www.xizai.com/trade/business/back/updateAccountStatus/" + artRecs.get(0).getOutid() + "/0";
        String result = HttpRequest.put(downOnUrl)
                .header("authorization", salePartner.getTwoOther())
                .execute()
                .body();
        JSONObject resultJson = JSONObject.parseObject(result);
        if (!"200".equals(resultJson.getString("code"))) {
            resultMap.put("code", 500);
        } else {
            resultMap.put("code", 200);
            String delUrl = "https://www.xizai.com/trade/business/back/deleteGoodsByAccountIdByMerchant?accountId=" + artRecs.get(0).getOutid();
            String delResult = HttpRequest.get(delUrl)
                    .header("authorization", salePartner.getTwoOther())
                    .execute()
                    .body();
            JSONObject delResultJson = JSONObject.parseObject(delResult);
            if ("200".equals(delResultJson.getString("code"))) {
                resultMap.put("code", 200);
            }
        }
        resultMap.put("msg", resultJson.getString("msg"));
        resultMap.put("req", JSONObject.toJSONString(artRecs.get(0).getOutid()));
        resultMap.put("res", result);
        return AjaxResult.success(resultMap);
    }
}
